"""
    4月优化：发送请求发送
"""
# _*_ coding:utf-8 _*_
import json
import os
import sys
import requests
import urllib3
# 2025-04修改
from API.config.read_conf import get_common_headers, get_config,get_url
from API.lib.changeheader import changeheader
from API.lib.parse_data import get_json
import logging

sys.path.append(os.path.dirname(os.path.dirname(__file__)))  # window环境适配的代码
# sys.path.append(os.path.abspath('..'))# linux环境适配的代码
urllib3.disable_warnings()


def sendRequests(apiData, ip=None):
    result = None
    """
        发送接口请求
        :param apiData:接口请求数据
        :return: 返回接口响应信息，以json格式
    """
    try:
        # 发送请求数据
        method = apiData["method"]
        path = apiData["url"]
        # 获取path配置
        path = get_url(ip,path)
        # 获取 headers 配置信息
        headers = get_common_headers(apiData["headers"])
        if 'Authorization' in headers:
            headers = changeheader(headers)
        # 处理请求参数
        params_data = None
        if apiData["params"]:
            params_data = get_json(apiData["params"])
        # 根据method方法选择参数类型
        if method == 'get':
            result = requests.get(url=path, headers=headers, params=params_data)
        elif method in ('post', 'put', 'patch'):
            # 根据Content-Type决定用data还是json
            if headers.get('Content-Type') == 'application/json':
                result = requests.request(method, url=path, headers=headers, json=params_data)
            else:
                result = requests.request(method, url=path, headers=headers, data=params_data)
        elif method == 'delete':
            result = requests.delete(url=path, headers=headers)
        else:
            raise ValueError(f"Error sendRequests method: {method}")
        logging.info("请求地址：%s 请求数据：%s 请求方法：%s 响应状态码：%s 请求头：%s",
                     path, params_data,method, result.status_code, result.request.headers)
        return result.text

    except Exception as e:
        logging.info(e)
